package com.demo.es.service;

import com.demo.es.entity.OrderDetail;
import com.demo.es.entity.OrderHeader;
import com.demo.es.repository.OrderRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ElasticsearchService {

    @Resource
    private OrderRepository orderRepository;

    /**
     * 主要测试将es字段是否支持保存List
     * @param orderSn 订单号
     */
    public void saveOrder(Long orderId, String orderSn) {
        OrderHeader orderHeader = new OrderHeader();
        orderHeader.setOrderSn(orderSn);
        orderHeader.setOrderId(orderId);
        orderHeader.setDateOfPurchase(new Date());
        orderHeader.setAddress(orderSn + " - 地址");
        orderHeader.setPrice(BigDecimal.ONE);

        orderRepository.save(orderHeader);
    }

    /**
     * 保存订单和订单明细在同一个doc内，明细是嵌套对象
     * @param orderId 订单id
     * @param orderSn 订单号
     */
    public void saveOrderAndDetail(Long orderId, String orderSn) {
        OrderHeader orderHeader = new OrderHeader();
        orderHeader.setOrderSn(orderSn);
        orderHeader.setOrderId(orderId);
        orderHeader.setDateOfPurchase(new Date());
        orderHeader.setAddress(orderSn + " - 地址");
        orderHeader.setPrice(BigDecimal.ONE);

        List<OrderDetail> orderDetails = Stream.of(1, 2).map(s ->
                new OrderDetail().setOrderId(orderId).setName("name" + s + orderSn).setSku(s + "_" + orderSn)
        ).collect(Collectors.toList());
        orderHeader.setDetail(orderDetails);

        orderRepository.save(orderHeader);
    }

    /**
     * 根据订单号查询订单信息
     * @param orderSn 订单号
     * @return 订单列表
     */
    public List<OrderHeader> queryOrder(String orderSn) {
        return orderRepository.findByOrderSnLike(orderSn);
    }

    /**
     * 根据订单号更新订单信息
     * @param orderSn 订单号
     * @param address 地址
     * @param price 价格
     */
    public void updateOrder(String orderSn, String address, BigDecimal price) {
        List<OrderHeader> orderHeaders = orderRepository.findByOrderSnLike(orderSn);
        orderHeaders.forEach(s -> {
            s.setAddress(address);
            s.setPrice(price);
        });

        orderRepository.saveAll(orderHeaders);
    }
}
